﻿using Dapper;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SkiaSharp;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SalesOutController : ControllerBase
    {
        private readonly sal_SalesOutService sal_salesOutService;
        private readonly MyDbContext myDbContext;
        public SalesOutController(MyDbContext myDb, sal_SalesOutService sal_SalesOutService)
        {
            myDbContext = myDb;
            this.sal_salesOutService = sal_SalesOutService;
        }

        /// <summary>
        /// 主表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<sal_sales_Out>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "out_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "sal_sales_Out"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<sal_sales_Out>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<sal_sales_Out> fenYe = new FenYe<sal_sales_Out>()
                {
                    SaleOutData = result,
                    Rows = row,
                };
                if (fenYe.SaleOutData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //销售出库主表添加
        [HttpPost]
        public async Task<IActionResult> AddOutMain([FromBody] sal_sales_Out sal_Sales_Out)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateSaleCode(maxCodeNumber);

            sal_Sales_Out.out_code = newCode;

            if (ModelState.IsValid)
            {
                int result = await sal_salesOutService.Add(sal_Sales_Out);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.sal_sales_Out
                .Where(w => w.out_code.StartsWith("XSCK"))
                .Select(w => w.out_code.Substring(12))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "01";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }

            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleCode(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "XSDD"、日期部分和数字部分
            return "XSCK" + dateString + codeString;
        }

        /// <summary>
        /// 从表表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<sal_sales_Out_C>> getFenYeC(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "OutID"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "sal_sales_Out_C"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<sal_sales_Out_C>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<sal_sales_Out_C> fenYe = new FenYe<sal_sales_Out_C>()
                {
                    tableData = result,
                    Rows = row,
                };
                if (fenYe.tableData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        /// <summary>
        /// 销售出库审核
        /// </summary>
        /// <param name="out_id"></param>
        /// <returns></returns>
        [HttpPost("{out_id}")]
        public async Task<IActionResult> AuditSalesOrder(int out_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOut = await myDbContext.sal_sales_Out
                .Include(so => so.sal_sales_out_c) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.out_id == out_id);

           

            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            if (salesOut == null || salesOut.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            // 检查从表sal_Orders是否有数据
            if (!salesOut.sal_sales_out_c.Any() || salesOut.sal_sales_out_c.All(order => order.IsDeleted))
                
                {
                return BadRequest("从表没有数据，不能进行审核");
            }

            // 检查退货状态，如果为1或2，则不能进行审核
            if (salesOut.out_Return_status == "2")
            {
                return BadRequest("该订单已经正在进行退货，不能进行审核");
            }

            try
            {
                // 审核销售订单
                salesOut.OutAuditStatus = true;
                salesOut.so_status = '2';
                salesOut.so_shipment_status = '1';
                salesOut.auditor = "Admin";
                salesOut.auditTime = DateTime.UtcNow;

                // 同时更新关联的销售订单状态
                var salesOrder = await myDbContext.sal_sales_orders
                    .FirstOrDefaultAsync(so => so.so_code == salesOut.out_code);
                if (salesOrder != null)
                {
                    salesOrder.so_status = salesOut.so_status; // 更新销售订单状态
                    salesOrder.so_shipment_status = salesOut.so_shipment_status;
                }

                if (salesOut.so_status == '2')
                {
                    
                    foreach (var returnItem in salesOut.sal_sales_out_c)
                    {
                        
                        var inv_otherOutbound = new inv_other_outbound
                        {
                            ioo_id = 0,
                            ioo_item_name = returnItem.orders_product_name,
                            ioo_specification = salesOut.out_code,
                            ioo_item_attributes = "产品",
                            ioo_unit = "包",
                            ioo_quantity = returnItem.outbound_quantity,
                            ioo_warehouse = returnItem.w_Name,
                            ioo_operators = salesOut.employee_name,
                            ioo_outbound_date = DateTime.Now,
                            ioo_type = "销售出库",
                            ioo_audit = false,
                            IsDeleted = false,
                            ioo_create_by = "Admin",
                            ioo_create_time = DateTime.Now,
                            ioo_update_by = "Admin",
                            ioo_update_time = DateTime.Now,
                        };
                        myDbContext.inv_other_outbound.Add(inv_otherOutbound);
                    }
                }

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，并已创建对应的销售出库单");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 销售出库删除主表
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{out_id}")]
        public async Task<string> FromDelete(int out_id)
        {
            var sal = await myDbContext.sal_sales_Out
                .Include(m => m.sal_sales_out_c)
                .SingleOrDefaultAsync(m => m.out_id == out_id);
            if (sal == null || sal.IsDeleted == true)
            {
                return "未找到对应的数据";
            }
            var undeletedFroms = sal.sal_sales_out_c.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }
            sal.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }

        /// <summary>
        /// 销售出库从表删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{OutID}")]
        public async Task<IActionResult> OutDelete(int OutID)
        {
            int result = await sal_salesOutService.Delete_C(OutID);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }

        /// <summary>
        /// 修改主表
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> UpdateClient(sal_sales_Out sal_Sales_Out)
        {
            if (ModelState.IsValid)
            {
                // 检查退货状态，如果为 "1" 或 "2"，则不允许修改
                if (sal_Sales_Out.out_Return_status == "1" || sal_Sales_Out.out_Return_status == "2")
                {
                    return BadRequest("修改失败：该订单已提交退货申请，不能进行修改！");
                }

                sal_Sales_Out.sal_sales_out_c = null;
                int result = await sal_salesOutService.Update(sal_Sales_Out);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        /// <summary>
        /// 从表修改
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update_C(sal_sales_Out_C data) 
        {
            if (ModelState.IsValid)
            {
                int result = await sal_salesOutService.Update_C(data);
                if (result > 0)
                {
                    return Ok("修改成功");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else 
            {
                return BadRequest(ModelState);
            }
        }

        /// <summary>
        /// 从表添加
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add_C(sal_sales_Out_C data)
        {
            if (ModelState.IsValid)
            {
                int result = await sal_salesOutService.Add_C(data);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

       
    }
}
